package organ

import (
	"encoding/csv"
	"os"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"go-papers/models"
	"go-papers/pkg/lognew"
	"go-papers/tools"
	"go-papers/tools/app"
	"go-papers/tools/app/msg"
)

// DownTeacherList
func DownTeacherList(c *gin.Context) {
	var data models.OrganTeacher
	var err error
	var pageSize = 10
	var pageIndex = 1

	if index := c.Request.FormValue("teacherId"); index != "" {
		data.TeacherId = tools.StrToInt(err, index)
	}
	data.TeacherName = c.Request.FormValue("teacherName")
	data.OrganName = c.Request.FormValue("organName")
	data.BrandName = c.Request.FormValue("brandName")
	data.WorkInfo = c.Request.FormValue("workInfo")
	data.CreateBy = c.Request.FormValue("createBy")
	data.UpdateBy = c.Request.FormValue("updateBy")
	data.ApprovalStatus = c.Request.FormValue("approvalStatus")
	data.UpdateStart = c.Request.FormValue("updateStart")
	data.UpdateEnd = c.Request.FormValue("updateEnd")

	data.ApprovalAt = c.Request.FormValue("approvalAt")
	data.ApprovalUserId = c.Request.FormValue("approvalUserId")
	data.ApprovalUserName = c.Request.FormValue("approvalUserName")
	uid := tools.GetUserIdStr(c)
	if uid == "" {
		app.OK(c, nil, "请登陆后操作数据")
		return
	}
	data.DataScope = tools.GetUserIdStr(c)
	result, count, err := data.GetPage(pageSize, pageIndex)
	if err != nil {
		app.ApiResp(c, -1, "数据操作失败："+err.Error(), nil)
		return
	}

	header := []string{"品牌名称", "机构名称", "教师ID", "教师姓名", "工作经历", "入职时间", "上传人", "更新时间", "状态", "审核人"} //标题
	cellist := [][]string{
		header,
	}
	cellist = DataToStringV4(result, cellist)

	page := count/pageSize + 1

	for i := 2; i <= page; i++ {
		pageIndex = i
		result, _, _ = data.GetPage(pageSize, pageIndex)
		if len(result) <= 0 {
			break
		}
		cellist = DataToStringV4(result, cellist)
	}

	// 创建文件
	filepath := "static/"
	filename := "Teacher_" + time.Now().Format("20060102150405") + ".csv"
	newFile, err := os.Create(filepath + filename)
	if err != nil {
		app.OK(c, nil, err.Error())
		return
	}
	defer func() {
		newFile.Close()

		err := os.Remove(filepath + filename)
		if err != nil {
			// 删除失败
			lognew.Info(c, "导出文件-清理失败", lognew.Fields{"file": filepath + filename, "err": err.Error()})
		}

	}()

	// 写入UTF-8
	newFile.WriteString("\xEF\xBB\xBF") // 写入UTF-8 BOM，防止中文乱码
	// 写数据到csv文件
	w := csv.NewWriter(newFile)
	// WriteAll方法使用Write方法向w写入多条记录，并在最后调用Flush方法清空缓存。
	w.WriteAll(cellist)
	w.Flush()

	c.File(filepath + filename)

}

// OrganTeacher
// "品牌名称",  "机构名称","教师ID","教师姓名","工作经历", "入职时间", "上传人", "更新时间","状态","审核人"
func DataToStringV4(list []models.OrganTeacher, data [][]string) [][]string {
	for i := 0; i < len(list); i++ {
		context := []string{
			list[i].BrandName,
			list[i].OrganName,
			strconv.Itoa(list[i].TeacherId),
			list[i].TeacherName,
			list[i].WorkInfo,
			list[i].TreacherRegister,
			list[i].CreateBy,
			list[i].UpdatedAt.Format("2006-01-02 15:04:05"),
			list[i].ApprovalStatus,
			list[i].ApprovalUserName,
		}
		data = append(data, context)
	}
	return data
}

func GetOrganTeacherList(c *gin.Context) {
	var data models.OrganTeacher
	var err error
	var pageSize = 10
	var pageIndex = 1

	if size := c.Request.FormValue("pageSize"); size != "" {
		pageSize = tools.StrToInt(err, size)
	}
	if index := c.Request.FormValue("pageIndex"); index != "" {
		pageIndex = tools.StrToInt(err, index)
	}
	if index := c.Request.FormValue("teacherId"); index != "" {
		data.TeacherId = tools.StrToInt(err, index)
	}
	data.TeacherName = c.Request.FormValue("teacherName")
	data.OrganName = c.Request.FormValue("organName")
	data.BrandName = c.Request.FormValue("brandName")
	data.WorkInfo = c.Request.FormValue("workInfo")
	data.CreateBy = c.Request.FormValue("createBy")
	data.UpdateBy = c.Request.FormValue("updateBy")
	data.ApprovalStatus = c.Request.FormValue("approvalStatus")
	data.UpdateStart = c.Request.FormValue("updateStart")
	data.UpdateEnd = c.Request.FormValue("updateEnd")

	data.ApprovalAt = c.Request.FormValue("approvalAt")
	data.ApprovalUserId = c.Request.FormValue("approvalUserId")

	data.ApprovalUserName = c.Request.FormValue("approvalUserName")

	data.DataScope = tools.GetUserIdStr(c)
	result, count, err := data.GetPage(pageSize, pageIndex)
	if err != nil {
		app.ApiResp(c, -1, "数据操作失败："+err.Error(), nil)
		return
	}

	app.PageOK(c, result, count, pageIndex, pageSize, "")
}

func GetOrganTeacher(c *gin.Context) {
	var data models.OrganTeacher
	data.TeacherId, _ = tools.StringToInt(c.Param("id"))
	result, err := data.Get()
	if err != nil {
		app.ApiResp(c, -2, "抱歉未找到相关信息："+err.Error(), nil)
		return
	}

	app.OK(c, result, "")
}

func InsertOrganTeacher(c *gin.Context) {
	var data models.OrganTeacher
	err := c.ShouldBindJSON(&data)

	//uid := tools.GetUserIdStr(c)

	var user models.SysUser
	uidInfo, _ := user.GetById(tools.GetUserId(c))
	if uidInfo.UserType == "3" {
		data.OrganId = uidInfo.OrganId
		data.OrganName = uidInfo.OrganName
	}

	data.UpdateBy = tools.GetUserIdStr(c)
	data.CreateBy = tools.GetUserIdStr(c)
	data.CreateByName = tools.GetUserName(c)
	data.UpdateByName = tools.GetUserName(c)
	if err != nil {
		app.ApiResp(c, -1, "数据解析失败："+err.Error(), nil)
		return
	}

	result, err := data.Create()
	if err != nil {
		app.ApiResp(c, -1, "数据操作失败："+err.Error(), nil)
		return
	}

	app.OK(c, result, "")
}

func UpdateOrganTeacher(c *gin.Context) {
	var data models.OrganTeacher
	err := c.BindWith(&data, binding.JSON)
	if err != nil {
		app.ApiResp(c, -1, "数据解析失败："+err.Error(), nil)
		return
	}

	var user models.SysUser
	uidInfo, _ := user.GetById(tools.GetUserId(c))
	if uidInfo.UserType == "3" {
		data.OrganId = uidInfo.OrganId
		data.OrganName = uidInfo.OrganName
	}

	data.UpdateBy = tools.GetUserIdStr(c)
	data.CreateBy = tools.GetUserIdStr(c)
	data.CreateByName = tools.GetUserName(c)
	data.UpdateByName = tools.GetUserName(c)

	result, err := data.Update(data.TeacherId)
	if err != nil {
		app.ApiResp(c, -1, "数据操作失败："+err.Error(), nil)
		return
	}

	app.OK(c, result, "")
}

func CheckOrganTeacher(c *gin.Context) {
	var data models.OrganTeacher
	var checkReq models.CheckReq
	err := c.BindWith(&checkReq, binding.JSON)
	if err != nil {
		app.ApiResp(c, -1, "数据解析失败："+err.Error(), nil)
		return
	}

	data.TeacherId = checkReq.Id
	data.ApprovalStatus = checkReq.ApprovalStatus
	data.ApprovalUserId = tools.GetUserIdStr(c)
	data.ApprovalUserName = tools.GetUserName(c)
	data.ApprovalAt = time.Now().Format("2006-01-02 15:04:05")
	result, err := data.Update(data.TeacherId)
	if err != nil {
		tools.HasError(err, "操作失败"+err.Error(), -1)
	}

	app.OK(c, result, "操作成功")
}

func DeleteOrganTeacher(c *gin.Context) {
	var data models.OrganTeacher

	IDS := tools.IdsStrToIdsIntGroup("id", c)
	_, err := data.BatchDelete(IDS)
	if err != nil {
		app.ApiResp(c, -1, "数据删除失败："+err.Error(), nil)
		return
	}

	app.OK(c, nil, msg.DeletedSuccess)
}
